import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:sprintf/sprintf.dart';

import 'model/data.dart';

class MsgPage extends StatefulWidget {
  const MsgPage({Key? key}) : super(key: key);

  @override
  State<MsgPage> createState() => _MsgPageState();
}

class _MsgPageState extends State<MsgPage> {
  List<Msg> _list = [];

  @override
  void initState() {
    super.initState();

    var box = Hive.box('box');
    _list = List<Msg>.from(box.get('msg', defaultValue: <dynamic>[]));
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("消息列表"),
      ),
      body: _list.isEmpty
          ? Center(
          child: Image.asset(
            "images/ee.png",
            width: 150,
          ))
          : ListView.separated(
          padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 10),
          itemBuilder: (_, index) => _itemWidget(index),
          separatorBuilder: (_, __) => Divider(),
          itemCount: _list.length),
    );
  }

  Widget _itemWidget(int index) {
    Msg msg = _list[index];
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(msg.time);
    String time = sprintf("${dateTime.year}.%02d.%02d %02d:%02d:%02d",[dateTime.month,dateTime.day,dateTime.hour,dateTime.minute,dateTime.second]);
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10.0),
      child: Column(
        children: [
          Text(msg.content),
          const SizedBox(height: 10,),
          Container(
            alignment: Alignment.bottomRight,
            child: Text(time,style: TextStyle(color: Colors.grey,fontSize: 13),),
          )
        ],
      ),
    );
  }
}
